package com.github.gaojh.mvc.filter;

import com.github.gaojh.server.http.HttpContext;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 高建华
 * @date 2019-01-15 09:41
 */
public class FilterChain {

    private List<Filter> filterList = new ArrayList<>();
    private int filterIndex = 0;

    public FilterChain() {
        this((Filter) null);
    }

    public FilterChain(Filter... filters) {
        for (Filter filter : filters) {
            addInterceptor(filter);
        }
    }

    public FilterChain(List<Filter> filters) {
        this.filterList.addAll(filters);
    }

    public void addInterceptor(Filter filter) {
        this.filterList.add(filter);
    }

    public void doBefore(HttpContext httpContext) throws Exception {
        if (!filterList.isEmpty()) {
            for (int i = 0; i < filterList.size(); i++) {
                this.filterIndex = i;
                Filter filter = filterList.get(i);
                if (!filter.doBefore(httpContext)) {
                    httpContext.setInterceptorBool(true);
                    if (httpContext.getResult() == null) {
                        httpContext.setResult("请求被拦截：" + httpContext.getHttpRequest().getUrl());
                    }
                    return;
                }
            }
        }
    }

    public void doAfter(HttpContext httpContext) throws Exception {
        if (!filterList.isEmpty()) {
            for (int i = this.filterIndex; i >= 0; i--) {
                Filter filter = filterList.get(i);
                filter.doAfter(httpContext);
            }
        }
    }

}
